/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package http

import (
	nhttp "net/http"

	"github.com/emicklei/go-restful"
)

type ResultData struct {
	Success bool        `json:"success"`
	Msg     interface{} `json:"msg"`
	Data    interface{} `json:"data,omitempty"`
}

func Ok(resp *restful.Response, msg interface{}) {
	resp.WriteAsJson(ResultData{
		Success: true,
		Msg:     msg,
	})
}

func OkWithData(resp *restful.Response, msg interface{}, data interface{}) {
	resp.WriteHeaderAndJson(nhttp.StatusOK, ResultData{
		Success: true,
		Msg:     msg,
		Data:    data,
	}, "application/json")
}

func Failed(resp *restful.Response, msg interface{}) {
	resp.WriteAsJson(ResultData{
		Success: false,
		Msg:     msg,
	})
}

func FailedWithStatus(resp *restful.Response, status int, msg interface{}) {
	resp.WriteHeaderAndJson(status, ResultData{
		Success: false,
		Msg:     msg,
	}, "application/json")
}

func OkWithFile(req *restful.Request, response *restful.Response, fileName, filePath string) {
	contentType := "application/octet-stream"
	fileContentDisposition := "attachment;filename=" + fileName
	response.AddHeader("Content-Type", contentType)
	response.AddHeader("Content-Disposition", fileContentDisposition)
	nhttp.ServeFile(response.ResponseWriter, req.Request, filePath)
	response.WriteHeader(200)
}
